package org.domain.sisbreve.entity.usertype;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.domain.sisbreve.entity.enums.BaseEnum;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;
import org.hibernate.util.ReflectHelper;

@SuppressWarnings({"unchecked", "rawtypes"})
public class EnumUserType implements UserType, ParameterizedType {

	private Class<Enum> enumClass;

	public void setParameterValues(Properties parameters) {
		String enumClassName = parameters.getProperty("enumClassName");
		if (enumClassName == null || enumClassName.equals(""))
			throw new HibernateException("Parametro enumClassName nao informado para esse EnumUserType!");
		try {
			this.enumClass = ReflectHelper.classForName(enumClassName);
		} catch (ClassNotFoundException ex) {
			throw new HibernateException("Classe enum " + enumClassName + " não encontrada", ex);
		}
	}

	public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
		String nomeColuna = names[0];

		String valorNoBanco = rs.getString(nomeColuna);

		Enum[] constantes = (Enum[]) this.enumClass.getEnumConstants();

		for (Enum e : constantes) {
			Object obj = (rs.wasNull()) ? null : Enum.valueOf(this.enumClass, e.name());
			if (obj == null) {
				return null;
			}
			try {
				Method method = obj.getClass().getMethod("getCodigo", new Class[0]);
				method.setAccessible(true);
				String valor = String.valueOf(method.invoke(obj, new Object[0]));
				if (valor.equals(valorNoBanco)) {
					return obj;
				}
			} catch (Exception e1) {
				throw new HibernateException("O enum " + obj.getClass() + " não extende a interface BaseEnum.", e1);
			}
		}
		return null;
	}

	public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
		if (value == null) {
			st.setNull(index, Hibernate.STRING.sqlType());
		} else if (value instanceof BaseEnum) {
			st.setObject(index, ((BaseEnum) value).getCodigo());
		} else {
			st.setString(index, value.toString());
		}
	}

	public Object assemble(Serializable cached, Object owner) throws HibernateException {
		return cached;
	}

	public Object deepCopy(Object value) throws HibernateException {
		return value;
	}

	public Serializable disassemble(Object value) throws HibernateException {
		return ((Serializable) value);
	}

	public boolean equals(Object x, Object y) throws HibernateException {
		if (x == y) {
			return true;
		}
		if ((x == null) || (y == null)) {
			return false;
		}
		return x.equals(y);
	}

	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}

	public boolean isMutable() {
		return false;
	}

	public Object replace(Object original, Object target, Object owner) throws HibernateException {
		return original;
	}

	public Class returnedClass() {
		return this.enumClass;
	}

	public int[] sqlTypes() {
		return new int[] { Hibernate.STRING.sqlType() };
	}
}
